package traces

import (
	"context"
	"github.com/dgryski/trifles/uuid"
)

var TraceIdHeader = "x-trace"

func WithTraceId(ctx context.Context, traceId string, autoCreate bool) context.Context {
	if traceId == "" {
		if !autoCreate {
			return ctx
		}
		traceId = NewTraceId()
	}
	return context.WithValue(ctx, TraceIdHeader, traceId)
}

func NewTraceId() string {
	return uuid.UUIDv4()
}

func GetTraceId(ctx context.Context) *string {
	traceId := ctx.Value(TraceIdHeader)
	if traceId == nil {
		return nil
	}
	s, ok := traceId.(string)
	if !ok {
		return nil
	}
	return &s
}
